package delete;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class delete_bene extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String oracleUser = "azienda";
    private String oraclePwd  = "azienda";
    private Connection conn;
    private String driver,oracle;
    private Statement st=null;
    private ResultSet rs=null;
	
    public delete_bene() {
        super();
    }
    
    public void init(ServletConfig sc) throws ServletException
    {
    	super.init(sc);
		driver = "oracle.jdbc.driver.OracleDriver";
		oracle = "jdbc:oracle:thin:@localhost:1521:xe";
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			conn = DriverManager.getConnection(oracle, oracleUser, oraclePwd);
			conn.setAutoCommit(false);
			st = conn.createStatement();
			rs = null;
	
			String codice 			= request.getParameter("txtCodice");
			String qry				= "select count(*) as totbeni from dotazione where bene = " + codice
									+ " union "
									+ "select count(*) as totbeni from assegnazione where bene = " + codice;
			
			rs=st.executeQuery(qry);
			rs.next();
			if(rs.getInt("totbeni")==0)
			{
				rs.close();
				st.executeUpdate("delete from bene where numeroinventariogenerico = " + codice);
				response.sendRedirect("adm/ben/ins_bene.jsp?deleted=1");
			}	
			else
			{
				response.sendRedirect("adm/ben/ins_bene.jsp?deleted=0");
			}
			
			st.close();
			conn.close();
			
			
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
}
